<template>
    <div class="share">
        <el-card class="card">
            <div slot="header" class="head">
                <div class="avatar">
                    <el-avatar :src="userInfo.avatar" :size="50"></el-avatar>
                </div>
                <div class="head between">
                    <div class="info">
                        <div class="user">
                            <span class="ellipsis">{{ userInfo.nickname }}</span>
                        </div>
                        <div class="file-info">
                            <div class="file-item">
                                <i class="el-icon-document"></i>
                                <span class="ellipsis">{{ fileInfo.filename }}</span>
                            </div>
                            <div class="file-item">
                                <i class="el-icon-time"></i>
                                <span>{{ fileInfo.createTime }}</span>
                            </div>
                        </div>
                    </div>
                    <div>
                        <el-button @click="saveCloud">保存到我的云盘</el-button>
                    </div>
                </div>
            </div>
            <div class="table">
                <div class="bread">
                    <el-breadcrumb separator=">">
                        <el-breadcrumb-item v-for="item, index in breadList" :key="index">
                            <span @click="toFolder(item.id)">{{ item.filename }}</span>
                        </el-breadcrumb-item>
                    </el-breadcrumb>
                </div>
                <el-table :data="fileList" style="width: 100%" @cell-mouse-enter="handleRowMouseEnter"
                    @cell-mouse-leave="handleRowMouseLeave" v-loading="isLoading" element-loading-text="拼命加载中">
                    <el-table-column type="selection" width="55">
                    </el-table-column>
                    <el-table-column label="文件名">
                        <template slot-scope="scope">
                            <div class="filename">
                                <MyFileImg :filename="scope.row.fileType" :folder="scope.row.folderType" size="32">
                                </MyFileImg>
                                <div>
                                    <el-link :underline="false" @click="openFile(scope.row)" class="ellipsis">{{
                                        scope.row.filename
                                    }}</el-link>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column width="100">
                        <template slot-scope="scope">
                            <div v-if="scope.row.show" class="table-more">
                                <div class="table-more-item" v-show="scope.row.folderType == 1">
                                    <el-tooltip class="item" effect="dark" content="下载" placement="top">
                                        <i class="el-icon-download" @click="download(scope.row)"></i>
                                    </el-tooltip>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                    <el-table-column prop="updateTime" label="修改时间" width="200">
                    </el-table-column>
                    <el-table-column label="大小" width="150">
                        <template slot-scope="scope">
                            {{ $global.getSize(scope.row.fileSize) }}
                        </template>
                    </el-table-column>
                </el-table>
                <div class="card-bottom">
                    <el-pagination background layout="prev, pager, next" @current-change="changePage"
                        :current-page="currPage" :page-size="pageSize" :total="totalPage">
                    </el-pagination>
                </div>
            </div>
        </el-card>

        <el-dialog title="下载进度" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-progress :text-inside="true" :stroke-width="20" :percentage="percentage" class="progress"></el-progress>
            <span slot="footer" class="dialog-footer">
                <el-button type="danger" @click="cancelDownload">取消下载</el-button>
            </span>
        </el-dialog>

        <el-dialog :visible.sync="isMove" title="保存文件">
            <MoveFile :file="moveFile" :t="t" :type="2"></MoveFile>
        </el-dialog>
    </div>
</template>

<script>
import axios from "axios"
import { getItem } from "@/utils/cookieUtil"
import MyFileImg from "@/components/my-file-img"
import MoveFile from '@/components/move-file'

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

export default {
    name: "check",
    components: {
        MyFileImg,
        MoveFile
    },
    data() {
        return {
            fileList: [],
            pageSize: 10,
            currPage: 1,
            totalPage: null,
            isLoading: false,
            // 面包屑数据
            breadList: [
                {
                    filename: "全部",
                    id: -1
                }
            ],
            fileInfo: {},
            userInfo: {},
            // 展示下载进度
            dialogVisible: false,
            // 下载进度
            percentage: 0,
            // 是否保存到我的云盘
            isMove: false,
            // 移动的文件
            moveFile: null,
            // 时间戳
            t: null,
        }
    },
    mounted() {
        this.getShareInfo()
        this.getFileShare()
    },
    methods: {
        handleRowMouseEnter(row) {
            // 在鼠标进入行时，隐藏该行的信息列
            row.show = true;
        },
        handleRowMouseLeave(row) {
            // 在鼠标离开行时，显示该行的信息列
            row.show = false;
        },
        async getFileShare() {
            this.isLoading = true
            var path = this.$route.query.path;
            let res = await this.$store.dispatch('getShareFile', {
                folderId: path == null ? 0 : path.substring(path.lastIndexOf("/") + 1, path.length),
                limit: this.pageSize,
                page: this.currPage,
                uuid: this.$route.params.uuid,
                status: 1
            })
            this.isLoading = false
            if (!res.success) {
                if (res.message != "请输入验证码") this.$global.resError(res)
                let code = this.$route.query.code
                if (code != null) this.$router.push("/check/share/" + this.$route.params.uuid + "?code=" + code);
                else this.$router.push("/check/share/" + this.$route.params.uuid);
            }
            else {
                res.data.list.forEach(item => {
                    item.show = false;
                });
                this.fileList = res.data.list
                this.totalPage = res.data.totalCount
            }
        },
        async getShareInfo() {
            var uuid = this.$route.params.uuid;
            let res = await this.$store.dispatch("getShareInfo", uuid)
            if (res.success) {
                this.fileInfo = res.data.fileInfo
                this.userInfo = res.data.userInfo
            }
            else this.$global.resError(res)
        },
        async openFile(item) {
            // 如果是文件夹
            if (item.folderType == 2) {
                this.$router.push({
                    path: this.$route.path,
                    query: {
                        path: (this.$route.query.path == null ? '' : this.$route.query.path) + "/" + item.id,
                    }
                })
                // 加入面包屑
                this.breadList.push(item)
            }
        },
        clearFileList() {
            this.fileList = []
            this.currPage = 1
        },
        changePage(page) {
            this.currPage = page
            this.getFileShare()
        },
        // 面包屑跳转路径
        toFolder(id) {
            if (id == -1) {
                // 若是全部
                this.breadList = [
                    {
                        filename: "全部",
                        id: -1
                    }
                ]
                this.$router.push({
                    path: this.$route.path,
                    query: {
                        category: this.$route.query.category
                    }
                })
            }
            else {
                // 不是全部
                var path = this.$route.query.path
                var routerPath = "/" + id
                this.$router.push({
                    path: this.$route.path,
                    query: {
                        category: this.$route.query.category,
                        path: path.substring(0, path.indexOf(routerPath) + routerPath.length)
                    }
                })
                let flag = true
                this.breadList = this.breadList.filter(item => {
                    if (item.id == id) {
                        flag = false
                        return true;
                    }
                    return flag;
                })
            }
        },
        // 下载文件
        async download(item) {
            this.dialogVisible = true
            axios.get("/api/fileShare/download/" + item.id,
                {
                    responseType: 'blob',
                    cancelToken: source.token,
                    headers: {
                        token: getItem("token"),
                    },
                    params: {
                        uuid: this.$route.params.uuid
                    },
                    onDownloadProgress: progressEvent => {
                        // 计算下载进度
                        const progress = Math.round(
                            (progressEvent.loaded * 100) / progressEvent.total
                        );
                        this.percentage = progress
                        if (progress == 100) {
                            this.$message.success("下载成功");
                            this.dialogVisible = false
                        }
                    }
                })
                .then((res) => {
                    if (!res) return
                    let blob = new Blob([res.data], { type: 'charset=utf-8' }) // 文件类型
                    let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
                    let url = window.URL.createObjectURL(blob);  // 创建下载链接
                    let aLink = document.createElement("a");    // 赋值给a标签的href属性
                    aLink.style.display = "none";
                    aLink.href = url;
                    aLink.setAttribute("download", filename);
                    document.body.appendChild(aLink);   // 将a标签挂载上去
                    aLink.click();          // a标签click事件
                    document.body.removeChild(aLink);  // 移除a标签
                    window.URL.revokeObjectURL(url);   // 销毁下载链接
                }).catch(function (error) {
                    console.log(error);
                })
        },
        saveCloud() {
            if (this.roleList.length === 0) {
                this.$message.warning("请先登录")
                return
            }
            this.moveFile = this.fileList[0]
            this.isMove = true
            this.t = Date.now()

        },
        handleClose(done) {
            this.percentage = 0
            done();
        },
        cancelDownload() {
            source.cancel();
            this.$message.success("取消下载成功")
            this.dialogVisible = false
        }
    },
    computed: {
        roleList() {
            return this.$store.state.user.roleList || []
        }
    },
    watch: {
        '$route.query': function (newVal, oldVal) {
            this.clearFileList()
            this.getFileShare()
        },
    },
}
</script>

<style scoped>
.share {
    height: 100%;
    width: 100%;
    position: relative;
    background: url(../check/images/share_bg.png);
    background-repeat: repeat-x;
    background-position: 0 bottom;
    background-color: #eef2f6;
}

.card {
    position: absolute;
    top: 5%;
    left: 50%;
    transform: translateX(-50%);
    width: 80%;
    height: 90%;
    overflow: auto;
}

.head {
    display: flex;
    align-items: center;
    color: white;
}

.avatar {
    width: 70px;
    text-align: center
}


.user {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.createTime {
    font-size: 13px;
}

::v-deep .el-card__header {
    background-color: #409EFF;
}

.username {
    font-size: 16px;
    font-weight: 550;
}

.center {
    text-align: center;
}

.between {
    width: 100%;
    justify-content: space-between;
}

.file-info {
    display: flex;
    align-items: center;
}

.file-item {
    font-size: 13px;
    font-weight: 550;
    margin-right: 10px;
    display: flex;
    align-items: center;
}

.file-item i {
    margin-right: 4px;
}

.table-more {
    display: flex;
    justify-content: space-around;
    align-items: center;
}

.table-more-item {
    cursor: pointer;
    font-size: 16px;
    color: #409EFF;
}

.filename {
    display: flex;
    align-items: center;
}

.table {
    position: relative;
}

.card-bottom {
    text-align: center;
    margin-top: 10px;
}

.bread {
    margin-bottom: 10px;
}

::v-deep .el-breadcrumb__inner {
    cursor: pointer !important;
}

.ellipsis {
    display: -webkit-box;
    overflow: hidden;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    text-overflow: ellipsis;
}

.progress {
    width: 350px;
    border-radius: 13px;
}
</style>